package thinlet.demo;

import java.awt.*;
import java.awt.event.*;
import thinlet.*;

class EventTestWidget extends Widget {
	
	private int prevId = 0;
	private String[] lines = { "", "", "", "", "" };
	
	public Metrics getPreferredSize(int preferredWidth) {
		Component comp = getComponent();
		FontMetrics fm = comp.getFontMetrics(comp.getFont());
		return new Metrics(128, fm.getHeight() * lines.length - fm.getLeading());
	}
	
	protected void process(AWTEvent e) {
		int id = e.getID();
		if (e instanceof MouseEvent) {
			String text = "-";
			switch (id) {
			case MouseEvent.MOUSE_ENTERED: text = "enter"; break;
			case MouseEvent.MOUSE_EXITED: text = "exit"; break;
			case MouseEvent.MOUSE_PRESSED: text = "press"; break;
			case MouseEvent.MOUSE_RELEASED: text = "release"; break;
			case MouseEvent.MOUSE_MOVED: text = "move"; break;
			case MouseEvent.MOUSE_DRAGGED: text = "drag"; break;
			case DRAG_ENTERED: text = "drag enter"; break;
			case DRAG_EXITED: text = "drag exit"; break;
			case DRAG_MOVED: text = "drag move"; break;
			case DRAG_RELEASED: text = "drag release"; break;
			case MouseWheelEvent.MOUSE_WHEEL: text = "wheel";
			}
			if (prevId != id) for (int i = 0; i < lines.length - 1; i++) lines[i] = lines[i + 1];
			MouseEvent me = (MouseEvent) e;
			lines[lines.length - 1] = text + ": " + me.getX() + ", " + me.getY();
			if (id == MouseEvent.MOUSE_PRESSED) requestFocus();
			repaint();
		}
		else if (e instanceof FocusEvent) {
			repaint();
		}
		else if (e instanceof KeyEvent) {
			KeyEvent ke = (KeyEvent) e;
			String text = "-";
			switch (id) {
			case KeyEvent.KEY_TYPED: text = "typed"; break;
			case KeyEvent.KEY_PRESSED: text = "press"; break;
			case KeyEvent.KEY_RELEASED: text = "release";
			}
			for (int i = 0; i < lines.length - 1; i++) lines[i] = lines[i + 1];
			lines[lines.length - 1] = text + ": " + KeyEvent.getKeyText(ke.getKeyCode()) + " " +
				KeyEvent.getKeyModifiersText(ke.getModifiers()) + ": " + ke.getKeyCode() + " " +
				ke.getKeyChar() + " " + ke.isActionKey() + " " + ke.getModifiers();
			repaint();
		}
		prevId = id;
	}
	
	protected void paint(Graphics g) {
		g.setColor(isFocused() ? Color.darkGray : Color.lightGray);
		g.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
		g.setColor(Color.black);
		FontMetrics fm = g.getFontMetrics();
		for (int i = 0; i < lines.length; i++) {
			g.drawString(lines[i], 0, fm.getAscent() + i * fm.getHeight());
		}
	}
}
